/*
 * @Author: yuki
 * @Date: 2025-11-04 21:26:15
 * @LastEditTime: 2025-11-06 18:39:18
 * @Description: 登录模块
 */
import type { User } from '@horoscope/shared';
import type { PayloadAction } from '@reduxjs/toolkit';
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

import { login as loginApi } from '@/request/api/auth';

export const fetchLogin = createAsyncThunk(
  'user/login',
  async (
    data: { username: string; password: string },
    { dispatch, rejectWithValue }
  ) => {
    try {
      const res = await loginApi(data);
      if (res.success) {
        window.localStorage.setItem('token', res.data?.token ?? '');

        if (res.data) {
          dispatch(login(res.data.userInfo));
        }
      } else {
        return rejectWithValue(res.message);
      }
    } catch (error) {
      return rejectWithValue((error as Error).message);
    }
  }
);

export interface IUserState {
  isLogin: boolean;
  showLoginModal: boolean;
  userInfo: User.IUserInfo;
}

const UserSlice = createSlice({
  name: 'user',
  initialState: {
    isLogin: false,
    showLoginModal: false,
    userInfo: {}
  } as IUserState,
  reducers: {
    login(state, action: PayloadAction<User.IUserInfo>) {
      state.isLogin = true;
      state.userInfo = action.payload;
    },
    logout(state) {
      state.isLogin = false;
      state.userInfo = {} as User.IUserInfo;
    },
    setUserInfo(state, action: PayloadAction<User.IUserInfo>) {
      state.userInfo = action.payload;
    },
    setShowLoginModal(state, action: PayloadAction<boolean>) {
      state.showLoginModal = action.payload;
    }
  }
});

export const { login, logout, setShowLoginModal, setUserInfo } =
  UserSlice.actions;

export default UserSlice.reducer;
